package com.wesley.growth;

import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;

/**
 * LRUCache
 *
 * @author WangPanYong
 * @since 2022/10/18 17:22
 */
public class LRUCache<K,V> implements Iterable<K>{
    /**
     * 最大容量
     */
    private final int max = 3;

    private final LinkedHashMap<K, V> cacheMap = new LinkedHashMap<>();

    public void cache(K key, V value) {
        if (cacheMap.containsKey(key)) {
            cacheMap.remove(key);
        } else if (cacheMap.size() >= max) {
            // 移除最早添加的元素
            var ite = cacheMap.keySet().iterator();
            cacheMap.remove(ite.next());
        }
        cacheMap.put(key, value);
    }

    @Override
    public Iterator<K> iterator() {
        return cacheMap.keySet().iterator();
    }

    public static void main(String[] args) {
        var lru = new LRUCache<String, Integer>();
        lru.cache("A", 1);
        lru.cache("B", 2);
        lru.cache("C", 3);

        lru.cache("D", 4);
        lru.cache("C", 10);
        System.out.println(
                " leave <- " +
                        StreamSupport.stream(lru.spliterator(), false)
                                     .map(Object::toString)
                                     .collect(Collectors.joining(" <- "))
        );
    }
}
